<?php
require_once ('library/Model/BaseModel.php');

/**
 *
 * @author Nguyen
 *        
 */
class Point extends BaseModel implements IModel{
	
	public function getNametrip(){
		$sql = 'select r.id as routeid,
					   p.name as name1,
					   b.name as name2						
				from trip as t left join route as r on t.route = r.id
					left join point as p on r.pointstart = p.id
						left join point as b on r.pointend = b.id where t.status = 1 and p.status = 1 and b.status = 1 and r.status = 1';
		return $this->db->fetchAll($sql);
	}
	
	public function getListGps(){
		$sql = 'select id from gps where status = 1';
		return $this->db->fetchAll($sql);
	}
	/* (non-PHPdoc)
	 * @see BaseModel::getall()
	 */
	public function getall($strlimit = NULL) {
		// TODO Auto-generated method stub
		$sql = 'select p.id,p.code,p.name,CONCAT_WS(" - ",p1.name,p2.name) as routename,p.position as rposition,p.latitude,p.longtitude,p.status
				from point as p
				left join point as p1 on p.route = p1.route and p1.position in(select min(p1.position) from point as p1 where p.route=p1.route)
				left join point as p2 on p.route = p2.route and p2.position in(select max(p2.position) from point as p2 where p.route=p2.route)
				order by p.id ASC '.$strlimit;
		return $this->db->fetchAll($sql);
	}
	/**
	 *  lay id va name cua point stt =1
	 */
	public function getNamePoint(){
		$sql = 'select id,name from point where status = 1';
		return $this->db->fetchAll($sql);
	}
	/* (non-PHPdoc)
	 * @see BaseModel::insert()
	 */
	public function insert(array $entity) {
		// TODO Auto-generated method stub
		$xsql = 'select position from point where route = '.$entity['route'].' order by position DESC';
		$x = $this->db->fetchRow($xsql);
		$entity['position'] = (int)$x['position'] + 1;
		$sql = "insert into point (";
		$c = $b = 0;
		foreach ( $entity as $key => $value ) {
			if ($c == 0) {
				$sql .= $key;
				$c = 1;
			} else
				$sql .= "," . $key;
		}
		$sql .= ")";
		$sql .= " values (";
		foreach ( $entity as $key => $value ) {
			if ($b == 0) {
				$sql .= "'" . $value . "'";
				$b = 1;
			} else
				$sql .= "," . "'" . $value . "'";
		}
		$sql .= ")";
		echo $sql;
		return $this->db->execute ( $sql );
	}
	public function getinfoPoint($idpoint){
		$sql = 'select * from point where id = '.$idpoint;
		return $this->db->fetchRow($sql);
	}
	public function getListPointInRoute($idroute){
		$sql = 'select * from point where route = '.$idroute;
		return $this->db->fetchAll($sql);
	}
	public function getListPointByTrip($tripid){
		$sql = 'select p.*, t.id as tid, r.id as rid, t.code as tcode,r.code as rcode  from point as p
				LEFT JOIN route as r ON p.route = r.id
				LEFT JOIN trip as t ON t.route = r.id
				 where t.id = '.$tripid;
		return $this->db->fetchAll($sql);
	}
}

?>